<script lang="ts">
  import {
    useSvelteFlow,
    type NodeProps,
    type XYPosition,
  } from "@xyflow/svelte";
  import NodeWrap from "../common/NodeWrap.svelte";
  import {
    create_edge,
    create_node,
    EDGE_TYPE_SMOOTH_STEP,
    type ExDrawNodeInfo,
  } from "$lib/api/board/board_draw";
  import SvelteMarkdown from "svelte-markdown";
  import { MessageSquareMore } from "lucide-svelte";
  import { drawStore } from "../../store.svelte";
  import { get_user_session } from "$lib/api/user";
  import { request } from "$lib/utils/request";
  import { getContext } from "svelte";
  import { writeText } from "@tauri-apps/plugin-clipboard-manager";
  import type { Store as ToastStore } from "@zag-js/toast";

  const toast: ToastStore = getContext("toast");

  const props: NodeProps = $props();
  const nodeInfo = $derived(props.data as ExDrawNodeInfo);

  const { fitView } = useSvelteFlow();

  function findPosition(): XYPosition {
    const pos = {
      x: nodeInfo.x,
      y: nodeInfo.y + nodeInfo.h + 200,
    };
    //列出子节点
    const childNodeIdList = drawStore.edgeList
      .filter((item) => item.edge_key.from_node_id == nodeInfo.node_id)
      .map((item) => item.edge_key.to_node_id);

    const childNodeList = drawStore.nodeList.filter((item) =>
      childNodeIdList.includes(item.node_id)
    );
    for (const childNode of childNodeList) {
      const newX = childNode.x + childNode.w + 200;
      if (newX > pos.x) {
        pos.x = newX;
      }
    }
    return pos;
  }

  async function createAskNode() {
    const sessionId = await get_user_session();
    //创建ask节点
    const pos = findPosition();
    const nodeRes = await request(
      create_node({
        session_id: sessionId,
        board_id: drawStore.boardInfo?.board_id ?? "",
        draw_id: drawStore.drawId,
        x: pos.x,
        y: pos.y,
        w: 200,
        h: 200,
        content: {
          LlmAskContent: {
            content: "",
          },
        },
        node_style: {
          bg_color: "bg-surface-200",
          border_width: "border-1",
          border_color: "bg-surface-200",
          font_color: "text-primary-900",
          layer: 10,
        },
      })
    );
    //创建连接
    await request(
      create_edge({
        session_id: sessionId,
        board_id: drawStore.boardInfo?.board_id ?? "",
        draw_id: drawStore.drawId,
        edge_key: {
          from_node_id: nodeInfo.node_id,
          from_handle: "b",
          to_node_id: nodeRes.node_id,
          to_handle: "t",
        },
        basic_info: {
          edge_type: EDGE_TYPE_SMOOTH_STEP,
          stroke_width: 3,
          color: "var(--color-secondary-900)",
          has_start_arrow: false,
          has_end_arrow: true,
          label: "",
          llm_link: true,
        },
      })
    );
    //调整布局
    fitView();
  }
</script>

<NodeWrap nodeProps={props} showBorder showBgColor showResizer>
  <div class="flex flex-col h-full">
    <div class="flex gap-2 pl-1">
      <MessageSquareMore />
      回答({nodeInfo.content.LlmAnswerContent?.provider_name ?? ""}/{nodeInfo
        .content.LlmAnswerContent?.model_name ?? ""})
    </div>
    <div
      class="m-2 p-1 text-wrap break-all ring-1 flex-1 overflow-auto nowheel"
    >
      <SvelteMarkdown
        source={nodeInfo.content.LlmAnswerContent?.content ?? ""}
      />
    </div>
    <div class="flex items-center justify-center gap-2">
      {#if (drawStore.boardInfo?.llm_list ?? []).length > 0 && !drawStore.readOnly}
        <button
          type="button"
          class="btn preset-filled-primary-900-100 mb-2"
          onclick={() => createAskNode()}>追问</button
        >
      {/if}
      <button
        type="button"
        class="btn preset-filled-primary-900-100 mb-2"
        onclick={() => {
          writeText(nodeInfo.content.LlmAnswerContent?.content ?? "");
          toast.create({
            title: "成功",
            description: "复制成功!",
            type: "success",
          });
        }}>复制内容</button
      >
    </div>
  </div>
</NodeWrap>
